package com.wangxiaoxuan.seckill.service.impl;

import com.wangxiaoxuan.seckill.pojo.User;
import com.wangxiaoxuan.seckill.service.CaptchaService;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 王小轩
 * @version 1.0
 * @date 2022年08月23日 15:23
 */
@Service
public class CaptchaServiceImp implements CaptchaService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取验证码
     * @param user
     * @param goodsId
     * @param response
     */
    @Override
    public void getCaptcha(User user, Long goodsId, HttpServletResponse response) {
        if(user==null || goodsId<0){
            return;
        }
        //设置请求头输出为图片类型
        response.setContentType("img/jpg");
        //设置不缓存，防止刷新验证码出现问题
        response.setHeader("Pargam","No-cache");
        response.setHeader("Cache-control","no-cache");
        //失效时间为0
        response.setDateHeader("Expires",0);
        //生成验证码
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 32, 3);
        //将验证码答案放到redis中
        redisTemplate.opsForValue().set("user:"+user.getId()+":"+goodsId,captcha.text());
        //输入验证码
        try {
            captcha.out(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 校验验证码
     * @param user
     * @param goodsId
     * @param captcha
     * @return
     */
    @Override
    public boolean checkCaptcha(User user, Long goodsId, String captcha) {
        if(user==null || goodsId<0||captcha==null){
            return false;
        }
        String checkCaptcha=(String) redisTemplate.opsForValue().get("user:"+user.getId()+":"+goodsId);
        return captcha.equals(checkCaptcha);
    }
}
